package c2.cross.business.championrace;

import cate.common.util.GameResult;
import cate.game.pvp.championrace.data.ChampionRaceRank;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.annotation.Transient;

import java.util.*;

public class ChampionRaceRankData {
    public List<ChampionRaceRank> rankList;
    @Transient
    private final Object rankLock = new Object();

    public void initialize() {
        if (rankList == null) {
            rankList = new ArrayList<>();
        }
    }

    public int getRankIndex(String roleUid) {
        if (StringUtils.isBlank(roleUid) || isEmpty()) {
            return -1;
        }
        synchronized (rankLock) {
            for (int i = 0; i < rankList.size(); ++ i) {
                if (StringUtils.equals(rankList.get(i).owner.uid, roleUid)) {
                    return i;
                }
            }
            return -1;
        }
    }

    public ChampionRaceRank getRankData(int index) {
        if (index >= size()) {
            return null;
        }
        ChampionRaceRank rank;
        synchronized (rankLock) {
            rank = rankList.get(index);
        }
        return rank;
    }

    public List<ChampionRaceRank> getRankList() {
        List<ChampionRaceRank> list;
        synchronized (rankLock) {
            list = new ArrayList<>(rankList);
        }
        return list;
    }

    public int size() {
        int size;
        synchronized (rankLock) {
            size = rankList.size();
        }
        return size;
    }

    public boolean isEmpty() {
        return size() == 0;
    }

    public void clear() {
        synchronized (rankLock) {
            rankList.clear();
        }
    }

    public void addRankDatas(List<ChampionRaceRank> rankList) {
        synchronized (rankLock) {
            this.rankList.clear();
            this.rankList.addAll(rankList);
            this.rankList.sort(Comparator.comparing(ChampionRaceRank::getWinCount, Comparator.reverseOrder())
                            .thenComparing(ChampionRaceRank::getValue, Comparator.reverseOrder()));
        }
    }

    public GameResult<Void> admire(int index, String roleUid) {
        GameResult<Void> r = new GameResult<>();
        if (index < 0 || index >= size()) {
            return r.fail("超出排行榜范围");
        }
        ChampionRaceRank roleRank = getRankData(index);
        if (Objects.isNull(roleRank)) {
            return r.fail("查不到此人数据");
        }
        if (StringUtils.equalsIgnoreCase(roleRank.getOwner().uid, roleUid)) {
            return r.fail("无法给自己点赞");
        }
        roleRank.admireNum += 1;
        return r;
    }
}
